package ui;

import javax.swing.*;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
import java.awt.*;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.List;

public class ClientChatFrame extends JFrame {
    public JTextArea smsContent = new JTextArea(23, 50);
    private JTextArea smsSend = new JTextArea(4, 40);
    public JList<String> onLineUsers = new JList<>();
    private JButton sendBn = new JButton("发送");
    private Socket socket;

    public ClientChatFrame() {
        initView();
        this.setVisible(true);
    }

    public ClientChatFrame(String nickname, Socket socket) {
        this();
        this.setTitle(nickname + "的聊天窗口");
        this.socket = socket;

        // 立即把客户端的socket管道交给一个独立的线程专门负责读取客户端socket从服务器接收到的消息
        new ClientReaderThread(socket, this).start();
    }


    private void initView() {
        this.setSize(800, 600);
        this.setLayout(new BorderLayout(5, 5));
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.setMinimumSize(new Dimension(600, 500));

        // 设置窗口背景色
        this.getContentPane().setBackground(new Color(0xECF0F1));

        // 设置字体
        Font font = new Font("SimKai", Font.PLAIN, 14);

        // 消息内容框
        smsContent.setFont(font);
        smsContent.setBackground(Color.WHITE);
        smsContent.setEditable(false);
        smsContent.setMargin(new Insets(10, 10, 10, 10));

        // 发送消息框
        smsSend.setFont(font);
        smsSend.setWrapStyleWord(true);
        smsSend.setLineWrap(true);
        smsSend.setBorder(new CompoundBorder(
                new MatteBorder(1, 1, 1, 1, new Color(0xBDC3C7)),
                new EmptyBorder(8, 8, 8, 8)
        ));
        smsSend.setBackground(Color.WHITE);

        // 在线用户列表
        onLineUsers.setFont(font);
        onLineUsers.setFixedCellWidth(120);
        onLineUsers.setFixedCellHeight(25);
        onLineUsers.setBackground(new Color(0xFFFFFF));
        onLineUsers.setSelectionBackground(new Color(0x3498DB));
        onLineUsers.setBorder(new EmptyBorder(5, 5, 5, 5));

        // 创建底部面板
        JPanel bottomPanel = new JPanel(new BorderLayout(5, 5));
        bottomPanel.setBackground(new Color(0xECF0F1));
        bottomPanel.setBorder(new EmptyBorder(5, 5, 5, 5));

        // 消息输入框
        JScrollPane smsSendScrollPanel = getScrollPane();

        // 发送按钮
        sendBn.setFont(font);
        sendBn.setBackground(new Color(0x2ECC71));
        sendBn.setForeground(Color.WHITE);
        sendBn.setFocusPainted(false);
        sendBn.setBorderPainted(false);
        sendBn.setCursor(new Cursor(Cursor.HAND_CURSOR));
        sendBn.setPreferredSize(new Dimension(80, 40));

        // 发送按钮点击事件
        sendBn.addActionListener(e -> {
            String msg = smsSend.getText();
            if (!msg.trim().isEmpty()) {
                sendMsgToServer(msg);
                smsSend.setText("");
            }
        });

        // 创建一个包含输入框和按钮的中间面板
        JPanel inputPanel = new JPanel(new GridBagLayout());
        inputPanel.setBackground(new Color(0xECF0F1));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.BOTH;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.gridx = 0;
        gbc.gridy = 0;
        inputPanel.add(smsSendScrollPanel, gbc);

        gbc.fill = GridBagConstraints.VERTICAL;
        gbc.weightx = 0.0;
        gbc.weighty = 0.0;
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.SOUTHEAST;
        inputPanel.add(sendBn, gbc);

        // 添加组件
        bottomPanel.add(inputPanel, BorderLayout.CENTER);

        // 用户面板标题
        JLabel onlineLabel = new JLabel("在线用户", JLabel.CENTER);
        onlineLabel.setFont(font);
        onlineLabel.setForeground(new Color(0x2C3E50));
        onlineLabel.setOpaque(true);
        onlineLabel.setBackground(new Color(0xECF0F1));
        onlineLabel.setBorder(new EmptyBorder(5, 0, 5, 0));

        // 用户列表面板
        JScrollPane userListScrollPanel = new JScrollPane(onLineUsers);
        userListScrollPanel.setBorder(new CompoundBorder(
                new MatteBorder(1, 1, 1, 1, new Color(0xBDC3C7)),
                new EmptyBorder(5, 5, 5, 5)
        ));
        userListScrollPanel.setPreferredSize(new Dimension(150, 500));
        userListScrollPanel.setBackground(new Color(0xECF0F1));

        // 中心消息面板标题
        JLabel messageLabel = new JLabel("聊天记录", JLabel.LEFT);
        messageLabel.setFont(font);
        messageLabel.setForeground(new Color(0x2C3E50));
        messageLabel.setOpaque(true);
        messageLabel.setBackground(new Color(0xECF0F1));
        messageLabel.setBorder(new EmptyBorder(5, 10, 5, 10));

        // 中心消息面板
        JScrollPane smsContentScrollPanel = getJScrollPane();

        // 创建主面板容器
        JPanel centerPanel = new JPanel(new BorderLayout());
        centerPanel.setBackground(new Color(0xECF0F1));
        centerPanel.add(messageLabel, BorderLayout.NORTH);
        centerPanel.add(smsContentScrollPanel, BorderLayout.CENTER);

        // 创建右侧面板容器
        JPanel eastPanel = new JPanel(new BorderLayout());
        eastPanel.setBackground(new Color(0xECF0F1));
        eastPanel.add(onlineLabel, BorderLayout.NORTH);
        eastPanel.add(userListScrollPanel, BorderLayout.CENTER);

        // 添加所有组件
        this.add(centerPanel, BorderLayout.CENTER);
        this.add(bottomPanel, BorderLayout.SOUTH);
        this.add(eastPanel, BorderLayout.EAST);

    }

    private JScrollPane getScrollPane() {
        JScrollPane smsSendScrollPanel = new JScrollPane(smsSend);
        smsSendScrollPanel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        smsSendScrollPanel.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

        // 自定义垂直滚动条外观
        JScrollBar sendScrollBar = smsSendScrollPanel.getVerticalScrollBar();
        sendScrollBar.setUI(new javax.swing.plaf.basic.BasicScrollBarUI() {
            @Override
            protected void configureScrollBarColors() {
                this.thumbColor = new Color(0xBDC3C7); // 滚动条颜色
                this.trackColor = new Color(0xECF0F1, true); // 轨道颜色（透明）
            }

            @Override
            protected JButton createDecreaseButton(int orientation) {
                JButton button = new JButton();
                button.setPreferredSize(new Dimension(0, 0));
                button.setMinimumSize(new Dimension(0, 0));
                button.setMaximumSize(new Dimension(0, 0));
                return button;
            }

            @Override
            protected JButton createIncreaseButton(int orientation) {
                JButton button = new JButton();
                button.setPreferredSize(new Dimension(0, 0));
                button.setMinimumSize(new Dimension(0, 0));
                button.setMaximumSize(new Dimension(0, 0));
                return button;
            }

            @Override
            protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setColor(thumbColor);
                // 圆角滚动条
                g2.fillRoundRect(thumbBounds.x + 3, thumbBounds.y, thumbBounds.width - 6, thumbBounds.height, 10, 10);
                g2.dispose();
            }
        });
        sendScrollBar.setPreferredSize(new Dimension(12, Integer.MAX_VALUE));
        sendScrollBar.setUnitIncrement(16);

        // 设置滚动条初始透明度为0（完全透明）
        sendScrollBar.setOpaque(false);
        sendScrollBar.setForeground(new Color(0xBDC3C7, false)); // 透明色

        // 鼠标事件监听器 - 悬浮时显示滚动条
        smsSendScrollPanel.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseEntered(java.awt.event.MouseEvent e) {
                // 悬浮时设置滚动条为不透明
                sendScrollBar.setOpaque(true);
                sendScrollBar.setForeground(new Color(0xBDC3C7, true)); // 不透明色
                sendScrollBar.repaint();
            }

            @Override
            public void mouseExited(java.awt.event.MouseEvent e) {
                // 离开时设置滚动条为透明
                sendScrollBar.setOpaque(false);
                sendScrollBar.setForeground(new Color(0xBDC3C7, false)); // 透明色
                sendScrollBar.repaint();
            }
        });

        smsSendScrollPanel.setBorder(new CompoundBorder(
                new MatteBorder(1, 1, 1, 1, new Color(0xBDC3C7)),
                new EmptyBorder(5, 5, 5, 5)
        ));
        smsSendScrollPanel.setPreferredSize(new Dimension(500, 150));
        return smsSendScrollPanel;
    }

    private JScrollPane getJScrollPane() {
        JScrollPane smsContentScrollPanel = new JScrollPane(smsContent);
        smsContentScrollPanel.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        smsContentScrollPanel.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

        // 自定义垂直滚动条外观
        JScrollBar contentScrollBar = smsContentScrollPanel.getVerticalScrollBar();
        contentScrollBar.setUI(new javax.swing.plaf.basic.BasicScrollBarUI() {
            @Override
            protected void configureScrollBarColors() {
                this.thumbColor = new Color(0xBDC3C7); // 滚动条颜色
                this.trackColor = new Color(0xECF0F1, true); // 轨道颜色（透明）
            }

            @Override
            protected JButton createDecreaseButton(int orientation) {
                JButton button = new JButton();
                button.setPreferredSize(new Dimension(0, 0));
                button.setMinimumSize(new Dimension(0, 0));
                button.setMaximumSize(new Dimension(0, 0));
                return button;
            }

            @Override
            protected JButton createIncreaseButton(int orientation) {
                JButton button = new JButton();
                button.setPreferredSize(new Dimension(0, 0));
                button.setMinimumSize(new Dimension(0, 0));
                button.setMaximumSize(new Dimension(0, 0));
                return button;
            }

            @Override
            protected void paintThumb(Graphics g, JComponent c, Rectangle thumbBounds) {
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setColor(thumbColor);
                // 圆角滚动条
                g2.fillRoundRect(thumbBounds.x + 3, thumbBounds.y, thumbBounds.width - 6, thumbBounds.height, 10, 10);
                g2.dispose();
            }
        });
        contentScrollBar.setPreferredSize(new Dimension(12, Integer.MAX_VALUE));
        contentScrollBar.setUnitIncrement(16);

        // 设置滚动条初始透明度为0（完全透明）
        contentScrollBar.setOpaque(false);
        contentScrollBar.setForeground(new Color(0xBDC3C7, false)); // 透明色

        // 鼠标事件监听器 - 悬浮时显示滚动条
        smsContentScrollPanel.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseEntered(java.awt.event.MouseEvent e) {
                // 悬浮时设置滚动条为不透明
                contentScrollBar.setOpaque(true);
                contentScrollBar.setForeground(new Color(0xBDC3C7, true)); // 不透明色
                contentScrollBar.repaint();
            }

            @Override
            public void mouseExited(java.awt.event.MouseEvent e) {
                // 离开时设置滚动条为透明
                contentScrollBar.setOpaque(false);
                contentScrollBar.setForeground(new Color(0xBDC3C7, false)); // 透明色
                contentScrollBar.repaint();
            }
        });

        smsContentScrollPanel.setBorder(new CompoundBorder(
                new MatteBorder(1, 1, 1, 1, new Color(0xBDC3C7)),
                new EmptyBorder(5, 5, 5, 5)
        ));
        return smsContentScrollPanel;
    }

    // 更新光标位置到文本框的末尾
    public void updateCursor() {
        smsContent.setCaretPosition(smsContent.getText().length());
    }

    // 更新在线用户列表
    public void updateOnLineUsers(String[] onLineNames) {
        onLineUsers.setListData(onLineNames);
    }

    // 更新群聊消息
    public void setMsgToWin(String msg) {
        smsContent.append(msg);
        smsContent.append("\n");
    }

    // 发送消息
    public void sendMsgToServer(String msg) {
        try {
            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
            dos.writeInt(2);
            dos.writeUTF(msg);
            dos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
